package Main.CS3.service;

import Main.CS3.dao.ContactDao;
import Main.CS3.entity.Contact;
import org.apache.ibatis.session.SqlSession;

import javax.swing.*;
import java.util.ArrayList;
import java.util.List;

public class ContactService {
    public Object[][] getResultContent(JTextField SearchText) {

        List<Contact> result = new ArrayList<Contact>();
        if (SearchText.getText().length() <= 0 || SearchText.getText() == null) {
            result = MySqlSession.getSession().getMapper(ContactDao.class).contactSelectAll();
        } else {
            result = MySqlSession.getSession().getMapper(ContactDao.class).contactSelectByName("%" + SearchText.getText() + "%");
        }
        Object[][] resultContent = new Object[result.size()][6];
        for (int i = 0; i < result.size(); i++) {
            Contact contact = result.get(i);
            resultContent[i][0] = contact.getCcode();
            resultContent[i][1] = contact.getCname();
            resultContent[i][2] = contact.getCaddress();
            resultContent[i][3] = contact.getCphone();
            resultContent[i][4] = contact.getCcode();
            resultContent[i][5] = contact.getCcode();

        }

        return resultContent;
    }

    public void contactDelete(Integer ccode){
        SqlSession session = MySqlSession.getSession();
        session.getMapper(ContactDao.class).contactDelete(ccode);
        session.commit();

    }
    public void contactAdd(Contact contact){
        SqlSession session = MySqlSession.getSession();
        ContactDao contactMapper = session.getMapper(ContactDao.class);

        System.out.println("添加操作："+contact);
        contactMapper.contactAdd(contact);
        //手动提交事务
        session.commit();
    }

    public void contactUpdate(Contact contact){
        SqlSession session = MySqlSession.getSession();
        ContactDao contactMapper = session.getMapper(ContactDao.class);


        System.out.println("修改操作："+contact);
        contactMapper.contactUpdate(contact);
        //手动提交事务
        session.commit();
    }


}
